<template>
  <div
    v-if="isRefresh"
    class="stop-reason full-height bg-white page-content content relative-position"
  >
    <public-filter
      ref="publicFilter"
      v-model="queryParams"
      :init="selfParams"
      :isShowProduct="true"
      @onSearchData="selfParams"
    >
      <div class="form-inline" style="padding-bottom: 14px">
        <q-btn
          class="btn"
          outline
          color="primary"
          :disable="!tableData.length"
          @click="exportExcelNew"
          label="导出Excel"
        />
        <q-toggle
          v-model="showScale"
          label="启用缩放"
          left-label
          style="position: absolute; right: 20px"
        />
      </div>
    </public-filter>
    <!-- 原因切换 -->
    <div style="flex: 1;padding: 0 20px;" class="margin-b-20 scroll-box">
      <!-- 图表的标题 -->
      <div
        class="flex items-center justify-between margin-b-20"
        style="margin-top: 6px"
      >
        <div class="flex items-center">
          <!-- <div>{{selLocation}}</div> -->
          <div>不良原因分析（ {{ oprof_start.date }}）</div>
          <div style="width: 264px; height: 26px; margin-left: 10px">
            <customized-switch
              :options="stopTypeOption"
              v-model="stopType"
              @change="onChangeStopType"
            />
          </div>
        </div>
      </div>
      <!-- echart 表 -->
      <div style="width: 100%; height: 400px" ref="dialogChart"></div>
      <!-- 显示的table -->
      <div class="padding-t-20">
        <q-table
          :data="tableData"
          :columns="columns"
          row-key="index"
          class="myTable scroll stick-last-col no-margin"
          :hide-bottom="!!tableData.length"
          ref="reportTable"
          :pagination="{ rowsPerPage: 0 }"
          id="reportTable"
          :loading="false"
          color="primary"
        >
          <template v-slot:body-cell-totalBadSeconds="props">
            <q-td>
              <q-btn
                flat
                color="primary"
                class="table-flat-btn"
                @click="showDialog(props.row)"
              >
                {{ props.row.totalBadSeconds }}
              </q-btn>
            </q-td>
          </template>
        </q-table>
      </div>
    </div>
    <stop-dialog
      ref="stopDialog"
      :rowData="rowData"
      :queryParams="rowParams"
      :stopType="stopType"
      @close="show = false"
      :show="show"
    ></stop-dialog>
  </div>
</template>

<script>
import echarts from 'echarts'
import refreshMixin from '../../assets/js/refresh-mixin'
import publicFilter from './components/public-filter'
import CustomizedSwitch from 'src/components/customized-switch'
import { getBadReports, exportBadCauseReports } from '../../boot/statistics/stop-reason'
import moment from 'moment'
import stopDialog from './components/disqualified-reason-dialog'
import GetPublicDate from './components/get-publice-date'
import STOPECHSRTD from './components/stop-echarts'
import _ from 'lodash'
import exportJs from './components/export'
// import XLSX from 'xlsx'
import { addListener } from 'resize-detector'
import { mapGetters } from 'vuex'
moment.locale('zh-cn')

export default {
  name: 'disqualified-reason',
  mixins: [refreshMixin],
  components: {
    publicFilter,
    stopDialog,
    CustomizedSwitch
  },
  data () {
    return {
      taleHead: [],
      showScale: false, // 是否可以缩放
      requestId: null, // 导出唯一标识
      chart: null,
      // 弹窗展示
      isRefresh: true,
      show: false,
      // 带过去的弹窗数据
      rowData: {},
      rowParams: {},
      // echarts后端请求的数据
      echartsData: {
        xValue: [],
        causeValue: [],
        percentage: []
      },
      // 原因类型
      causeType: {
        // 横向坐标值
        xValue: [],
        // 原因
        causeValue: [],
        // 百分比
        percentage: []
      },
      cause: {
        // 横向坐标值
        xValue: [],
        // 原因
        causeValue: [],
        // 百分比
        percentage: []
      },
      // 原因类别
      stopTypeOption: [
        {
          value: '1',
          label: '按原因类别查看'
        },
        {
          value: '2',
          label: '按原因查看'
        }
      ],
      stopType: '1',
      // 查询条件
      // 停机原因 日期 设备数量
      oprof_start: {
        date: ''
      },
      columnsClone: [],
      gloabalColums: [],
      tableData: [],
      tableDataClone: [],
      queryParams: {
        // 查询区条件
        dateRange: [
          moment(new Date())
            .subtract(1, 'days')
            .toDate(),
          new Date()
        ],
        dateData: [
          moment(
            moment(new Date())
              .subtract(1, 'days')
              .toDate()
          ).format('YYYY-MM-DD'),
          moment(new Date()).format('YYYY-MM-DD')
        ],
        dateType: 'date',
        location: {
          id: ''
        }, // 所在位置
        // 防止切换变换了dateType
        sumbitDate: '',
        devices: [],
        product: null
      }
    }
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'client'
    ]),
    columns () {
      let columns = [
        {
          name: 'indexId',
          label: '序号',
          field: 'indexId',
          align: 'left'
        },
        {
          name: this.stopType === '1' ? 'causeGroupName' : 'causeName',
          required: true,
          label: '原因',
          align: 'left',
          field: this.stopType === '1' ? 'causeGroupName' : 'causeName',
          format: val => `${val}`
        }
      ]
      columns = [
        ...columns,
        ...this.columnsClone,
        {
          name: 'totalBadSeconds',
          label: '合计',
          field: 'totalBadSeconds',
          align: 'left'
        }
      ]
      return columns
    }
  },
  created () { },
  watch: {
    echartsData: {
      handler (newPro) {
        this.getInitChart(newPro)
      },
      deep: true
    },
    showScale (val) {
      this.getInitChart(this.echartsData)
    }
  },
  methods: {
    exportTable () {
      let columns = [
        {
          label: '序号'
        },
        {
          label: '原因'
        }
      ]
      columns = [
        ...columns,
        ...this.columnsClone,
        {
          label: '合计'
        }
      ]
      columns = columns.map(item => item.label)
      return columns
    },
    /**
       * 全局刷新数据
       */
    refreshInfo () {
      this.isRefresh = false
      this.$refs.publicFilter.onResetSearch()
      this.$nextTick(() => {
        this.isRefresh = true
      })
    },
    // echart 计算 y轴累计百分比
    getpercentageY (val) {
      const arr = []
      const sum = _.sum(val.map(v => Number(v))).toFixed(1)
      const deepValue = _.cloneDeep(val).map(v => Number(v))
      for (let i = 0; i < val.length; i++) {
        const member = _.sum(deepValue.slice(0, i + 1))
        arr[i] = ((member / sum) * 100).toFixed(1)
      }
      return arr
    },
    // 查询接口
    selfParams (data) {
      const getPublicDate = new GetPublicDate(
        this.queryParams.dateRange,
        this.queryParams.dateType
      )
      switch (this.queryParams.dateType) {
        case 'date':
          this.queryParams.dateData = getPublicDate._setDay()
          this.queryParams._getTableHeader = getPublicDate._getTableHeaderDay()
          break
        case 'week':
          this.queryParams.dateData = getPublicDate._setWeek()
          this.queryParams._getTableHeader = getPublicDate._getTableHeaderWeek(
            this.queryParams
          )
          break
        case 'month':
          this.queryParams.dateData = getPublicDate._setYear()
          this.queryParams._getTableHeader = getPublicDate._getTableHeaderMonth(
            this.queryParams
          )
          break
      }
      // 显示日期设备上
      this.oprof_start.date = getPublicDate._setReasonDate().join('~')
      // 由自组件传来数据动态设置table表头
      this.columnsClone = this.queryParams._getTableHeader
      // 获取数据
      this.getBadReports(this.queryParams)
    },
    // 切换原因,进行改变E charts显示数据
    onChangeStopType (val) {
      if (val === '1') {
        this.echartsData = this.causeType
        this.tableData = this.tableDataClone[0]
      } else {
        this.echartsData = this.cause
        this.tableData = this.tableDataClone[1]
      }
    },
    // 初始化Echarts表格
    getInitChart (data) {
      this.chart = echarts.init(this.$refs.dialogChart)
      this.chart.setOption(new STOPECHSRTD({ ...data, id: '数量', isDisabled: this.showScale }).option)
    },
    // 动态展示E chart
    setChartList () {
      // 原因类别
      Object.keys(this.causeType).map(v => {
        this.causeType[v] = []
      })
      this.tableDataClone[0]
        .map(v => {
          this.causeType.xValue.push(v.causeGroupName)
          this.causeType.causeValue.push(Number(v.totalBadSeconds))
        })
      this.causeType.percentage = this.getpercentageY(
        this.causeType.causeValue)
      // 原因查看
      Object.keys(this.cause).map(v => {
        this.cause[v] = []
      })
      this.tableDataClone[1].map(v => {
        this.cause.xValue.push(v.causeName)
        this.cause.causeValue.push(Number(v.totalBadSeconds))
      })
      this.cause.percentage = this.getpercentageY(
        this.cause.causeValue)
      // 绘制E chart
      // 1===>类别 2===原因
      this.echartsData = Object.assign(
        {},
        this.stopType === '1' ? this.causeType : this.cause
      )
    },
    // 合计展示
    showDialog (val) {
      this.rowData = val
      this.rowParams = _.cloneDeep(this.queryParams)
      this.rowParams.dateType = this.sumbitDate
      this.show = true
    },
    // // 导出xls
    // download () {
    //   let workbook = document.querySelector('#reportTable')
    //   let sheet = XLSX.utils.table_to_sheet(workbook, { raw: true })
    //   try {
    //     exportJs.openDownloadDialog(exportJs.sheet2blob(sheet), '不良原因报表.xlsx')
    //   } catch (error) {
    //     console.log(error)
    //   }
    // },
    // 导出xls 样式 // 前端导出不用了
    exportList () {
      const companyName = this.userInfo.company_name ? this.userInfo.company_name : '语桢物联'
      const stopType = this.stopType === '1' ? '按原因类别查看' : '按原因查看'
      const stopReason = `不良原因分析(${this.oprof_start.date}) | ${stopType} `
      const position = `所在位置: ${this.queryParams.location && this.queryParams.location.label}`
      const tableHead = this.exportTable()
      const tableData = this.getTableData(this.tableData, tableHead)
      let location = this.queryParams.location && this.queryParams.location.label
      let data1 = '', data2 = ''
      if (this.queryParams && this.queryParams.dateRange.length > 0) {
        data1 = this.getDate(this.queryParams.dateRange[0])
        data2 = this.getDate(this.queryParams.dateRange[1])
      }
      const excelName = `${data1}-${data2}-${location}-不良原因分析报表`
      exportJs.exportCustomExcel(companyName, stopReason, position, tableHead, tableData, excelName)
    },
    getParamExcelHead () {
      let columns = [
        {
          name: '序号',
          field: 'string'
        },
        {
          name: '原因',
          field: 'string'
        }
      ]
      columns = [
        ...columns,
        ...this.columnsClone,
        {
          name: '合计',
          field: 'string'
        }
      ]
      columns = columns.map(item => {
        return {
          name: item.name,
          field: 'string'
        }
      })
      return columns
    },
    // 修改成后端导出
    exportExcelNew () {
      // console.log(this.queryParams)
      const params = {
        causeType: this.stopType,
        schemeLevel: this.queryParams && this.queryParams.location.level,
        schemeLevelId: this.queryParams && this.queryParams.location.id,
        workshopName: this.queryParams && this.queryParams.workshopName,
        excelHead: this.getParamExcelHead(),
        deviceIds: this.queryParams.devices[0] === 'all' ? [] : this.queryParams.devices,
        productIds: this.queryParams.product || ''
      }
      switch (this.queryParams.dateType) {
        case 'date':
          params.type = 1
          params.startDate = this.queryParams.dateData[0] || ''
          params.endDate = this.queryParams.dateData[1] || ''
          break
        case 'week':
          params.type = 2
          params.startWeek = this.queryParams.dateData[0] || ''
          params.endWeek = this.queryParams.dateData[1] || ''
          break
        case 'month':
          params.type = 3
          params.startMonth = this.queryParams.dateData[0] || ''
          params.endMonth = this.queryParams.dateData[1] || ''
          break
      }
      console.log(params)
      this.$q.loading.show()
      const names = [{ name: '' }]
      const res = this.$getUploadPath(names, '')
      this.requestId = res.fileNameNew
      params['requestId'] = res.fileNameNew
      this.onSubscribe()
      exportBadCauseReports(params).then(res => {
        if (res.code !== '1200') {
          this.$showErrTips('导出异常，请稍后重试')
          this.closeUbscribeTopic()
        }
      }).catch(res => {
        console.log(res)
        this.closeUbscribeTopic()
      })
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      let location = this.queryParams.location && this.queryParams.location.label
      let excelName = `${this.getDate(this.queryParams.dateRange[0])}-${this.getDate(this.queryParams.dateRange[1])}-${location}-不良原因分析报表`

      await this.$saveFileForBlob(msg.data, `${excelName}.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.$q.loading.hide()
      this.client.unsubscribe(`${this.requestId}`)
    },
    getDate (date) {
      return moment(date).format('YYYYMMDD')
    },
    getTableData (tableData, tableHead) {
      let result = []
      this.tableData.forEach(v1 => {
        // 总计
        let totalHaltingSeconds = 0
        const v1KesArr = Object.keys(v1)
        const item = []
        tableHead.forEach((v2, index) => {
          if (v2 === '序号') {
            item.push(v1.indexId)
          } else if (v2 === '原因') {
            if (this.stopType === '1') {
              item.push(v1.causeGroupName)
            } else {
              item.push(v1.causeName)
            }
          } else if (v2 === '合计') {
            item.push(totalHaltingSeconds)
          } else {
            let findI = v2
            if (this.queryParams.dateType === 'month') {
              findI = v2.split('-').join('')
            } else if (this.queryParams.dateType === 'week') {
              findI = moment(this.queryParams.dateRange[0]).format('YYYY') + v2.split('第').join('').split('周')[0]
            }
            if (this.isShow(v1KesArr, findI)) {
              let i = this.isShow(v1KesArr, findI)
              totalHaltingSeconds += v1[i] * 1
              item.push(v1[i])
            } else {
              item.push('')
            }
          }
        })
        result.push(item)
      })
      return result
    },
    isShow (arr, item) {
      let flag = ''
      arr.forEach(i => {
        if (item.indexOf(String(i)) > -1) {
          flag = i
        }
      })
      return flag
    },
    setOprofNum (val) {
      this.oprof_start.num = this.queryParams.devices[0] === 'all' ? val : this.queryParams.devices.length
    },
    // 初始化查询接口
    getBadReports (val) {
      const params = {
        deviceIds: val.devices[0] === 'all' ? [] : val.devices,
        startDate: val.dateData[0],
        endDate: val.dateData[1],
        schemeLevel: val.location.level,
        schemeLevelId: val.location.id,
        dateType: val.dateType,
        productIds: val.product,
        causeType: this.stopType
      }
      this.sumbitDate = val.dateType
      getBadReports(params).then(res => {
        // const ret = res.data.filter(v => v.totalBadSeconds > 0)
        const ret = res.data
        this.tableHead = ret // 导出报表获取数据 设置全局拿到表格数据
        // 如果原因为未填写 添加原因id 原因组id
        ret.map((v, i) => {
          const item = v
          item.indexId = i + 1
          if (v.causeName === '未填写') {
            item.causeId = -1
            item.causeGroupId = -1
            item.causeGroupName = '未分类'
          }
          // 打开日期数组,把数据平分到parent数组中

          item.causeName = v.causeGroupName + '/' + v.causeName
          return item
        })
        // 总设备
        this.oprof_start.num = ret.reduce((num, item) => {
          num = item.deviceCount + num
          return num
        }, 0)
        // 日期当中区分日周月字段
        const member = {
          date: 'date',
          week: 'week',
          month: 'yearMonth'
        }
        this.tableDataClone = [
          this.setCauseGroup(ret, member[val.dateType]),
          this.setCause(ret, member[val.dateType])
        ].map(v => {
          let item = _.sortBy(v, 'totalBadSeconds').reverse().map((v, i) => {
            const y = v
            y.indexId = i + 1
            return y
          })
          return item
        })
        // 查询初始化数据为按原因类别查看
        this.tableData =
          this.stopType === '1'
            ? _.cloneDeep(this.tableDataClone[0])
            : _.cloneDeep(this.tableDataClone[1])
        this.setChartList()
      })
    },
    // return 类型arr
    // 原因类型查看 reports ===> reports 后期要换
    setCauseGroup (val, dateType) {
      const p = _.cloneDeep(val)
      let arr = _.uniqBy(p, 'causeGroupId')
      p.map(v => {
        arr.map(j => {
          if (v.causeGroupId === j.causeGroupId && v.causeId !== j.causeId) {
            j.reports = [...j.reports, ...v.reports]
          }
        })
      })
      arr.map((v, i) => {
        const item = v
        const array = []
        v.reports.map(j => {
          array.push(j.badSeconds)
        })
        item.reports = this.keyPlusValue(v.reports, dateType)
        if (item.reports) {
          item.reports.map(y => {
            item[y.date] = y.badSeconds
          })
        }
        item.totalBadSeconds = _.sum(array)
      })
      arr = arr.filter(v => v.totalBadSeconds > 0)
      return arr
    },
    // return 原因arr
    setCause (val, dateType) {
      let p = val
      p.map(v => {
        const item = v
        if (v.reports) {
          v.reports.map(j => {
            item[j[dateType]] = j.badSeconds
          })
        }
      })
      p = p.filter(v => v.totalBadSeconds > 0)
      return p
    },
    // key相同,value想加
    keyPlusValue (arr, dateType) {
      const result = arr.reduce((obj, item) => {
        if (!obj[item[dateType]]) {
          obj[item[dateType]] = 0
        }
        obj[item[dateType]] += item.badSeconds
        return obj
      }, {})
      return Object.keys(result).map(key => ({
        date: key,
        badSeconds: result[key]
      }))
    }
  },
  mounted () {
    addListener(this.$refs.dialogChart, this.$utils.debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100))
    // window.addEventListener('resize', () => {
    //   this.chart.resize()
    // })
  }
}
</script>
<style scoped lang='stylus'>
.stop-reason {
  >>>.borderless .q-field__ {
    &control, &append {
      height: 21px;
      min-height: 21px;
      padding-left: 5px;
    }

    &control-container {
      line-height: 21px;
      padding: 0;
    }

    &native {
      padding: 0;
    }
  }

  >>>.q-field__marginal {
    font-size: 16px;
    color: black;
    font-weight: 400;
    text-align: right;
  }

  .scroll-box {
    overflow-y: scroll;

    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
      background-color: rgba(95, 119, 253, 0);
      transition: all 0.3s;

      &-thumb {
        border-radius: 6px;
        background-color: rgba(95, 119, 253, 0);
        transition: all 0.3s;
      }

      &-track {
        margin-left: -6px;
        padding-top: 48px;
        background-color: transparent;
        width: 0;
      }
    }

    &:hover::-webkit-scrollbar-thumb {
      background-color: rgba(95, 119, 253, 0.5);
    }
  }
}
</style>
